package com.mainbo.modular.system.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.mainbo.core.shiro.SessionKey;
import com.mainbo.core.shiro.ShiroKit;
import com.mainbo.modular.jms.model.ClassUserMessage;
import com.mainbo.modular.listener.Listenable;
import com.mainbo.modular.system.dao.PtAccountMapper;
import com.mainbo.modular.system.dao.PtClassMapper;
import com.mainbo.modular.system.model.PtAccount;
import com.mainbo.modular.system.model.PtClass;
import com.mainbo.modular.system.model.PtClassUser;
import com.mainbo.modular.system.dao.PtClassUserMapper;
import com.mainbo.modular.system.model.Teacher;
import com.mainbo.modular.system.model.meta.MetaUtils;
import com.mainbo.modular.system.service.IPtClassUserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 班级用户表 服务实现类
 * </p>
 *
 * @author moshang
 * @since 2020-02-28
 */
@Service
public class PtClassUserServiceImpl extends ServiceImpl<PtClassUserMapper, PtClassUser> implements IPtClassUserService {

    private static final Logger logger= LoggerFactory.getLogger(PtClassUserServiceImpl.class);
    @Resource
    private PtClassUserMapper ptClassUserMapper;
    @Resource
    private PtAccountMapper accountMapper;
    @Resource
    private PtClassMapper classMapper;
    @Override
    public Map<Integer, Teacher> getSubjectTeacherMap(String classId) {
        EntityWrapper<PtClassUser> wrapper = new EntityWrapper<>();
        wrapper.eq("class_id",classId);
        wrapper.eq("type",PtClassUser.TYPE_TEACHER);
        List<PtClassUser> cuList = ptClassUserMapper.selectList(wrapper);
        Map<Integer, Teacher> subjectTeacherMap = new HashMap<Integer, Teacher>();
        for (PtClassUser temp : cuList) {
            Teacher t = new Teacher();
            t.setId(temp.getUserId());
            t.setName(temp.getUserName());
            subjectTeacherMap.put(temp.getSubjectId(), t);
        }
        return subjectTeacherMap;
    }

    @Override
    public void saveOrUpdateClassUser(ClassUserMessage classUserVo, Integer userType) {
        PtAccount account = ShiroKit.getSessionAttr(SessionKey.CURRENT_USER);// 当前登录账号
        if (userType == PtClassUser.TYPE_TEACHER) {
            EntityWrapper<PtClassUser> cu = new EntityWrapper<>();
            cu.eq("class_id",classUserVo.getClassId());
            cu.eq("type",userType);
            List<PtClassUser> cuList = ptClassUserMapper.selectList(cu);
            // 先删除
            if (cuList != null && cuList.size() > 0) {
                for (PtClassUser temp : cuList) {
                    ptClassUserMapper.deleteById(temp.getId());
                }
            }
        }
        // 批量插入有效的对应关系

        List<PtClassUser> classUserList = classUserVo.getClassUserList();
        Map<String, PtClassUser> userMap = new HashMap<String, PtClassUser>();
        if (classUserList != null && classUserList.size() > 0) {
            Iterator<PtClassUser> it = classUserList.iterator();
            while (it.hasNext()) {
                PtClassUser temp = it.next();
                if (StringUtils.isBlank(temp.getUserName()) || StringUtils.isBlank(temp.getUserId())) {
                    it.remove();
                } else {
                    PtClassUser c = userMap.get(temp.getUserId());
                    if (c != null && userType == PtClassUser.TYPE_STUDENT) { // 如果是学生，则不可以有重复录入
                        it.remove();
                    } else {
                        userMap.put(temp.getUserId(), temp);
                        temp.setAccount(accountMapper.selectById(temp.getUserId()).getAccount());
                        temp.setClassId(classUserVo.getClassId());
                        temp.setOrgId(classUserVo.getOrgId());
                        temp.setType(userType);
                        temp.setCrtDttm(new Date());
                        temp.setCrtId(account.getUserInfo().getId());
                        temp.setEnable(true);
                        if (classUserVo.getSchoolYear() != null) {
                            temp.setSchoolYear(classUserVo.getSchoolYear());
                        } else {
                            temp.setSchoolYear(MetaUtils.getSchoolYearProvider().getCurrentSchoolYear(classUserVo.getOrgId()));
                        }
                    }
                }
            }
            insertBatch(classUserList);
        }
        if (userType == PtClassUser.TYPE_TEACHER) {
           // LoggerUtils.updateLogger(LoggerModule.ORGMANAGE, "组织机构管理——班级管理——任课教师设置——设置任课教师，班级ID:{}", classUserVo.getClassId());
        } else if (userType == PtClassUser.TYPE_STUDENT) {
            //LoggerUtils.updateLogger(LoggerModule.ORGMANAGE, "组织机构管理——班级管理——学生管理——配置学生，班级ID:{}", classUserVo.getClassId());
        }
    }

    @Override
    public List<PtClassUser> findStudents(PtClassUser classUser) {
        return ptClassUserMapper.findStudents(classUser);
    }

    @Override
    public List<PtClassUser> copyClassUsers(String oldClassId, Integer userType, Integer schoolYear) {
        PtClass newClassInfo = null;
        List<PtClassUser> newList = null;
        try {
            if (!com.mainbo.utils.StringUtils.isEmpty(oldClassId)) {
                newClassInfo = new PtClass();
                newClassInfo.setFromClassId(oldClassId);
                newClassInfo = classMapper.selectOne(newClassInfo);
                Set<String> userIds = new HashSet<String>();
                if (userType != null && PtClassUser.TYPE_STUDENT == userType.intValue()) {
                    EntityWrapper<PtClassUser> existStudent = new EntityWrapper<>();
                    existStudent.eq("type",PtClassUser.TYPE_STUDENT);
                    existStudent.eq("school_year",schoolYear);
                    existStudent.eq("org_id",newClassInfo.getOrgId());
                    existStudent.setSqlSelect("user_id");
                    List<PtClassUser> listAll = ptClassUserMapper.selectList(existStudent);
                    for (PtClassUser classUser : listAll) {
                        userIds.add(classUser.getUserId());
                    }
                }
                if (newClassInfo != null) {
                    EntityWrapper<PtClassUser> cu = new EntityWrapper<>();
                    cu.eq("class_id",oldClassId);
                    cu.eq("type",userType);
                    List<PtClassUser> cuList = ptClassUserMapper.selectList(cu);
                    newList = new ArrayList<>();
                    if (!CollectionUtils.isEmpty(cuList)) {
                        for (PtClassUser classUser : cuList) {
                            if (userType != null && PtClassUser.TYPE_STUDENT == userType && userIds.contains(classUser.getUserId())) {
                                continue;
                            }
                            classUser.setClassId(newClassInfo.getId());
                            classUser.setSchoolYear(schoolYear);
                            classUser.setCrtDttm(new Date());
                            newList.add(classUser);
                        }
                    }
                    this.insertBatch(newList);
                }
            }
        } catch (Exception e) {
            logger.info("ClassUserServiceImpl--->copyClassUsers--> error!,reason,{}", e);
            return null;
        }
        return newList;
    }

    @Override
    public List<PtClassUser> findClassStudentListByClassId(PtClassUser um, Integer graduateState, String classIds) {
         List<String>classIdList=Arrays.asList(classIds.split(","));
        List<PtClassUser> rs = ptClassUserMapper.findClassStudentListByClassId(um,graduateState,classIdList);

        return rs;
    }
}
